<?php

/**
* a webappkit tool to execute unit tests using a test database.
* sometimes you can't or don't want to use mock database connectors
* but don't want either to mess up your real data.
*
* this tool creates a fake database before issuing tests, and drop it after.
* insert the fake database definition into tool configuration file as this :
* [db]
* name = "fake database name"
* ; following data is optional, current connection will be used if existing
* host = ""
* user = ""
* pwd = ""
* [tables]
* ; name = "SQL creation command on a single line"
* mytable = "CREATE TABLE mytable(id primary key integer not null, value varchar(128))"
* [data]
* ; anykey = "row insertion command on a single line"
*/
class SimpleTestMysqlGroupTool extends SimpleTestGroupTool {
	
	function Factory($kit,$cfg) {
		return new SimpleTestMysqlGroupTool($kit,$cfg);
	}
	
	var $cfg=array(
		'db'=>array(
			'name'=>'test'
			,'encoding'=>'utf8'
			,'drop'=>true));
	
	function _init() {
		$this->db_name=isset($this->cfg['db']['name'])?$this->cfg['db']['name']:'test';
		$this->db_encoding=isset($this->cfg['db']['encoding'])?$this->cfg['db']['encoding']:'utf8';
	}

	function setUp() {
		// connecting
		// creating test database
		$sql='CREATE DATABASE '.$this->db_name.' CHARACTER SET '.$this->db_encoding;
		if (!mysql_query($sql)) {
			trigger_error("could not create database {$this->db_name} using query $sql",E_USER_WARNING);
		}
		// switching to new database
		if (!mysql_select_db($this->db_name)) {
			trigger_error("could not switch to test database {$this->db_name}",E_USER_ERROR);
			// DO NOT ISSUE TEST TO ANOTHER DB !!!
			exit;
		}
		// creating tables
		foreach ($this->cfg['tables'] as $table => $sql) {
			if (!mysql_query($sql)) {
				trigger_error("could not create table {$table} using query $sql",E_USER_WARNING);
			}
		}
		// dumping test data
		foreach ($this->cfg['data'] as $line => $sql) {
			if (!mysql_query($sql)) {
				trigger_error("could not insert row {$line} using query $sql",E_USER_WARNING);
			}
		}
	}
	
	function tearDown() {
		// dropping test database
		if ($this->cfg['db']['drop']) {
			$sql = 'DROP DATABASE '.$this->db_name;
			if (!mysql_query($sql)) {
				trigger_error("could not drop database {$this->db_name} using query $sql",E_USER_WARNING);
			}
		}
	}
}
?>